package com.ruicar.afs.cloud.apply.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.apply.business.condition.WorkflowAgencyTaskCondition;
import com.ruicar.afs.cloud.apply.business.mapper.WorkflowAgencyTaskMapper;
import com.ruicar.afs.cloud.apply.business.service.WorkflowAgencyTaskService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyConditionApprovalCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCarDetailsService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyChannelInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyConditionApprovalService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.vo.ValueVo;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyDiscountDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.CostTypeEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @description: 待办任务
 * @author: sijun.yu
 * @date: 2020/8/6 16:14
 */
@Service
@Slf4j
@AllArgsConstructor
public class WorkflowAgencyTaskServiceImpl extends ServiceImpl<WorkflowAgencyTaskMapper, WorkflowAgencyTask> implements WorkflowAgencyTaskService {
    private final ApplyConditionApprovalService applyConditionApprovalService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final ApplyFinancingItemsService applyFinancingItemsService;
    private final ApplyDiscountDetailsService applyDiscountDetailsService;
    private final ApplyChannelInfoService applyChannelInfoService;

    /**
     * @param condition
     * @return
     */
    @Override
    public Map getApplyConditionApprovalInfo(ApplyConditionApprovalCondition condition) {
        String applyNo = condition.getApplyNo();
        String costType = null;
        String isSub = null;
        if (StringUtil.isEmpty(applyNo)) {
            return null;
        }
        BigDecimal addAmount = BigDecimal.ZERO;
        Map conditionApprovalVO = new HashMap<>(6);
        Map map = new HashMap<>(4);
        Map newTotalInfo = new HashMap<>(6);
        Map oldTotalInfo = new HashMap<>(6);
        Map carCostDetails = new LinkedHashMap(6);
        Map addCostDetails = new HashMap<>(6);
        List<FinFinancingItems> resultList = new ArrayList<FinFinancingItems>();
        ApplyOrderInfo orderInfo = applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        ApplyCarDetails carDetailsByApplyNo = applyCarDetailsService.getCarDetailsByApplyNo(applyNo);
        List<FinFinancingItems> financingItemsList = applyFinancingItemsService.getFinancingItemsList(applyNo, carDetailsByApplyNo.getId());
        ApplyChannelInfo channelInfoByApplyNo = this.applyChannelInfoService.getChannelInfoByApplyNo(applyNo);
        if (CollectionUtil.isNotEmpty(financingItemsList)) {
            conditionApprovalVO.put("isAdditional", ApplyConstants.ONE);
        } else {
            conditionApprovalVO.put("isAdditional", ApplyConstants.ZERO);
        }
        log.info("附条件核准-融资项:{}", financingItemsList);
        for (FinFinancingItems finFinancingItems : financingItemsList) {
            if (ObjectUtil.isNotNull(finFinancingItems)) {
                FinFinancingItems financingItems = finFinancingItems;
                FinFinancingItems items = new FinFinancingItems();
                items.setId(financingItems.getId());
                items.setApplyNo(financingItems.getApplyNo());
                items.setCarId(financingItems.getCarId());
                items.setFinanceItemCode(financingItems.getFinanceItemCode());
                items.setFinanceItemName(financingItems.getFinanceItemName());
                items.setFinanceItemAmt(financingItems.getFinanceItemAmt());
                List<FinFinancingItems> sonList = applyFinancingItemsService.getApplyFinancingItemsList(applyNo, financingItems.getId());
                if (sonList != null && sonList.size() > 0) {
                    items.setSonList(sonList);
                }
                addAmount = addAmount.add(financingItems.getFinanceItemAmt());
                resultList.add(items);
            }
        }
        ApplyConditionApproval conditionApproval = applyConditionApprovalService.getOne(Wrappers.<ApplyConditionApproval>query().lambda()
                .eq(StringUtil.isNotEmpty(applyNo), ApplyConditionApproval::getApplyNo, applyNo));
        if (ObjectUtil.isNotNull(conditionApproval)) {
            JSONObject approveContent = JSONObject.parseObject(conditionApproval.getApproveContent());
            //信审传来的
            List<FinCostDetails> finCostDetailsList = approveContent.getJSONArray("finCostDetailsList").toJavaList(FinCostDetails.class);
            if (ObjectUtil.isNotNull(orderInfo)) {
                orderInfo.setChannelName(channelInfoByApplyNo.getChannelName());
                conditionApprovalVO.put("orderInfo", orderInfo);
            }
            //查询融资信息
            List<FinCostDetails> costDetailsList = applyCostDetailsService.getCostDetailsList(applyNo);
            //旧
            if (CollectionUtil.isNotEmpty(costDetailsList)) {
                ValueVo oldCarValue = new ValueVo();
                ValueVo oldAddValue = new ValueVo();
                BigDecimal contractAmt;
                BigDecimal downPayAmt;
                BigDecimal discountAmt;
                BigDecimal totalInterest;
                BigDecimal totalRent;
                BigDecimal loanAmt;
                //遍历，车贷，附加贷
                for (FinCostDetails finCostDetails : costDetailsList) {
                    //车款
                    if (CostTypeEnum.CARAMT.getCode().equals(finCostDetails.getCostType())) {
                        contractAmt = finCostDetails.getContractAmt();
                        downPayAmt = finCostDetails.getDownPayAmt();
                        discountAmt = finCostDetails.getDiscountAmt();
                        totalInterest = finCostDetails.getTotalInterest();
                        totalRent = finCostDetails.getTotalRent();
                        loanAmt = finCostDetails.getLoanAmt();
                        oldCarValue.setGuidePrice(carDetailsByApplyNo.getGuidePrice());
                        oldCarValue.setDownPayScale(finCostDetails.getDownPayScale());
                        oldCarValue.setDownPayAmt(downPayAmt);
                        oldCarValue.setTotalDiscountAmt(discountAmt);
                        oldCarValue.setLoanAmt(loanAmt);
                        oldCarValue.setTotalInterest(totalInterest);
                        oldCarValue.setTotalRent(totalRent);
                        oldCarValue.setTotalContractAmount(contractAmt);
                        oldCarValue.setAddAmount(addAmount);
                        if (finCostDetails.getTailPayAmt() != null) {
                            oldCarValue.setTailPayAmt(finCostDetails.getTailPayAmt());
                        }
                        if (finCostDetails.getTailPayScale() != null) {
                            oldCarValue.setTailPayScale(finCostDetails.getTailPayScale());
                        }
                        if (finCostDetails.getCustRate() != null) {
                            oldCarValue.setCustRate(finCostDetails.getCustRate());
                        }
                        if (finCostDetails.getMonthPayAmt() != null) {
                            oldCarValue.setMonthPay(finCostDetails.getMonthPayAmt());
                        }
                        oldCarValue.setLoanAmt(loanAmt);
                        oldCarValue.setLoanLimit(finCostDetails.getLoanTerm());
                        carCostDetails.put("oldCarValue", oldCarValue);
                        carCostDetails.put("costType", finCostDetails.getCostType());
                        carCostDetails.put("discountOption", finCostDetails.getDiscountType());
                        carCostDetails.put("isTail", finCostDetails.getIsTail());
                    } else if (CostTypeEnum.AFFIXAMT.getCode().equals(finCostDetails.getCostType())) {
                        //附加贷
                        contractAmt = finCostDetails.getContractAmt();
                        downPayAmt = finCostDetails.getDownPayAmt();
                        discountAmt = finCostDetails.getDiscountAmt();
                        totalInterest = finCostDetails.getTotalInterest();
                        totalRent = finCostDetails.getTotalRent();
                        loanAmt = finCostDetails.getLoanAmt();
                        oldAddValue.setTotalContractAmount(contractAmt);
                        oldAddValue.setDownPayAmt(downPayAmt);
                        oldAddValue.setTotalInterest(totalInterest);
                        oldAddValue.setTotalRent(totalRent);
                        oldAddValue.setLoanAmt(loanAmt);
                        oldAddValue.setTotalDiscountAmt(discountAmt);
                        oldAddValue.setDownPayScale(finCostDetails.getDownPayScale());
                        if (finCostDetails.getTailPayAmt() != null) {
                            oldAddValue.setTailPayAmt(finCostDetails.getTailPayAmt());
                        }
                        if (finCostDetails.getTailPayScale() != null) {
                            oldAddValue.setTailPayScale(finCostDetails.getTailPayScale());
                        }
                        if (finCostDetails.getCustRate() != null) {
                            oldAddValue.setCustRate(finCostDetails.getCustRate());
                        }
                        if (finCostDetails.getMonthPayAmt() != null) {
                            oldAddValue.setMonthPay(finCostDetails.getMonthPayAmt());
                        }
                        oldAddValue.setLoanAmt(finCostDetails.getLoanAmt());
                        oldAddValue.setLoanLimit(finCostDetails.getLoanTerm());
                        oldAddValue.setDiscountOption(finCostDetails.getDiscountType());
                        addCostDetails.put("oldAddValue", oldAddValue);
                        addCostDetails.put("isTail", finCostDetails.getIsTail());
                        addCostDetails.put("costType", finCostDetails.getCostType());
                        addCostDetails.put("discountOption", finCostDetails.getDiscountType());
                    }
                    isSub = finCostDetails.getIsSubProduct();
                    costType = finCostDetails.getCostType();
                    conditionApprovalVO.put("isSubProduct", isSub);
                }
                if (oldAddValue.getTotalDiscountAmt() != null) {
                    oldTotalInfo.put("totalDiscountAmt", oldCarValue.getTotalDiscountAmt().add(oldAddValue.getTotalDiscountAmt()));
                } else {
                    oldTotalInfo.put("totalDiscountAmt", oldCarValue.getTotalDiscountAmt());
                }
                if (oldAddValue.getTotalInterest() != null) {
                    oldTotalInfo.put("totalInterest", oldCarValue.getTotalInterest().add(oldAddValue.getTotalInterest()));
                } else {
                    oldTotalInfo.put("totalInterest", oldCarValue.getTotalInterest());
                }
                if (oldAddValue.getTotalRent() != null) {
                    oldTotalInfo.put("totalRent", oldCarValue.getTotalRent().add(oldAddValue.getTotalRent()));
                } else {
                    oldTotalInfo.put("totalRent", oldCarValue.getTotalRent());
                }
                if (oldAddValue.getTotalDiscountAmt() != null) {
                    oldTotalInfo.put("totalcontAmt", oldCarValue.getTotalDiscountAmt().add(oldAddValue.getTotalDiscountAmt()));
                } else {
                    oldTotalInfo.put("totalcontAmt", oldCarValue.getTotalDiscountAmt());
                }
                if (oldAddValue.getDownPayAmt() != null) {
                    oldTotalInfo.put("totalFirstAmt", oldCarValue.getDownPayAmt().add(oldAddValue.getDownPayAmt()));
                } else {
                    oldTotalInfo.put("totalFirstAmt", oldCarValue.getDownPayAmt());
                }
                if (oldAddValue.getTotalContractAmount() != null) {
                    oldTotalInfo.put("totalcontAmt", oldCarValue.getTotalContractAmount().add(oldAddValue.getTotalContractAmount()));
                } else {
                    oldTotalInfo.put("totalcontAmt", oldCarValue.getTotalContractAmount());
                }
                if (oldAddValue.getLoanAmt() != null) {
                    oldTotalInfo.put("totalLoanAmt", oldCarValue.getLoanAmt().add(oldAddValue.getLoanAmt()));
                } else {
                    oldTotalInfo.put("totalLoanAmt", oldCarValue.getLoanAmt());
                }
                map.put("oldTotalInfo", oldTotalInfo);
                //贴息列表
                List<FinDiscountDetails> details = applyDiscountDetailsService.getDiscountDetailsList(applyNo, costType);
                if (CollectionUtil.isNotEmpty(details)) {
                    carCostDetails.put("discountList", details);
                }
            }
            //新
            if (finCostDetailsList.size() > 0) {
                ValueVo newCarValue = new ValueVo();
                ValueVo newAddValue = new ValueVo();
                BigDecimal contractAmt;
                BigDecimal downPayAmt;
                BigDecimal discountAmt;
                BigDecimal totalInterest;
                BigDecimal totalRent;
                BigDecimal loanAmt;
                for (FinCostDetails finCostDetails : finCostDetailsList) {
                    //车款
                    if (CostTypeEnum.CARAMT.getCode().equals(finCostDetails.getCostType())) {
                        //合同总额
                        contractAmt = finCostDetails.getContractAmt();
                        downPayAmt = finCostDetails.getDownPayAmt();
                        discountAmt = finCostDetails.getDiscountAmt();
                        totalInterest = finCostDetails.getTotalInterest();
                        totalRent = finCostDetails.getTotalRent();
                        loanAmt = finCostDetails.getLoanAmt();
                        if (finCostDetails.getTailPayScale() != null) {
                            newCarValue.setTailPayScale(finCostDetails.getTailPayScale());
                        }
                        if (finCostDetails.getTailPayAmt() != null) {
                            newCarValue.setTailPayAmt(finCostDetails.getTailPayAmt());
                        }
                        newCarValue.setTotalContractAmount(contractAmt);
                        newCarValue.setDownPayAmt(downPayAmt);
                        newCarValue.setTotalDiscountAmt(discountAmt);
                        newCarValue.setTotalInterest(totalInterest);
                        newCarValue.setTotalRent(totalRent);
                        newCarValue.setLoanAmt(loanAmt);
                        newCarValue.setAddAmount(addAmount);
                        newCarValue.setCustRate(finCostDetails.getCustRate());
                        newCarValue.setMonthPay(finCostDetails.getMonthPayAmt());
                        newCarValue.setGuidePrice(carDetailsByApplyNo.getGuidePrice());
                        newCarValue.setDownPayScale(finCostDetails.getDownPayScale());
                        newCarValue.setLoanLimit(finCostDetails.getLoanTerm());
                        carCostDetails.put("newCarValue", newCarValue);
                    } else if (CostTypeEnum.AFFIXAMT.getCode().equals(finCostDetails.getCostType())) {
                        contractAmt = finCostDetails.getContractAmt();
                        downPayAmt = finCostDetails.getDownPayAmt();
                        discountAmt = finCostDetails.getDiscountAmt();
                        totalInterest = finCostDetails.getTotalInterest();
                        totalRent = finCostDetails.getTotalRent();
                        loanAmt = finCostDetails.getLoanAmt();
                        if (finCostDetails.getTailPayScale() != null) {
                            newAddValue.setTailPayScale(finCostDetails.getTailPayScale());
                        }
                        if (finCostDetails.getTailPayAmt() != null) {
                            newAddValue.setTailPayAmt(finCostDetails.getTailPayAmt());
                        }
                        newAddValue.setTotalContractAmount(contractAmt);
                        newAddValue.setDownPayAmt(downPayAmt);
                        newAddValue.setTotalDiscountAmt(discountAmt);
                        newAddValue.setTotalInterest(totalInterest);
                        newAddValue.setTotalRent(totalRent);
                        newAddValue.setLoanAmt(loanAmt);
                        newAddValue.setCustRate(finCostDetails.getCustRate());
                        newAddValue.setMonthPay(finCostDetails.getMonthPayAmt());
                        newAddValue.setDownPayScale(finCostDetails.getDownPayScale());
                        newAddValue.setLoanLimit(finCostDetails.getLoanTerm());
                        addCostDetails.put("newAddValue", newAddValue);
                    }
                }
                if (newAddValue.getTotalDiscountAmt() != null) {
                    newTotalInfo.put("totalDiscountAmt", newCarValue.getTotalDiscountAmt().add(newAddValue.getTotalDiscountAmt()));
                } else {
                    newTotalInfo.put("totalDiscountAmt", newCarValue.getTotalDiscountAmt());
                }
                if (newAddValue.getTotalInterest() != null) {
                    newTotalInfo.put("totalInterest", newCarValue.getTotalInterest().add(newAddValue.getTotalInterest()));
                } else {
                    newTotalInfo.put("totalInterest", newCarValue.getTotalInterest());
                }
                if (newAddValue.getTotalRent() != null) {
                    newTotalInfo.put("totalRent", newCarValue.getTotalRent().add(newAddValue.getTotalRent()));
                } else {
                    newTotalInfo.put("totalRent", newCarValue.getTotalRent());
                }
                if (newAddValue.getTotalDiscountAmt() != null) {
                    newTotalInfo.put("totalcontAmt", newCarValue.getTotalDiscountAmt().add(newAddValue.getTotalDiscountAmt()));
                } else {
                    newTotalInfo.put("totalcontAmt", newCarValue.getTotalDiscountAmt());
                }
                if (newAddValue.getDownPayAmt() != null) {
                    newTotalInfo.put("totalFirstAmt", newCarValue.getDownPayAmt().add(newAddValue.getDownPayAmt()));
                } else {
                    newTotalInfo.put("totalFirstAmt", newCarValue.getDownPayAmt());
                }
                if (newAddValue.getTotalContractAmount() != null) {
                    newTotalInfo.put("totalcontAmt", newCarValue.getTotalContractAmount().add(newAddValue.getTotalContractAmount()));
                } else {
                    newTotalInfo.put("totalcontAmt", newCarValue.getTotalContractAmount());
                }
                if (newAddValue.getLoanAmt() != null) {
                    newTotalInfo.put("totalLoanAmt", newCarValue.getLoanAmt().add(newAddValue.getLoanAmt()));
                } else {
                    newTotalInfo.put("totalLoanAmt", newCarValue.getLoanAmt());
                }
                map.put("newTotalInfo", newTotalInfo);
            }
            if (ApplyConstants.ZERO.equals(isSub)) {
                carCostDetails.put("finItemList", resultList);
            } else {
                addCostDetails.put("finItemList", resultList);
            }
            conditionApprovalVO.put("totalInfo", map);
            conditionApprovalVO.put("carCostDetails", carCostDetails);
            conditionApprovalVO.put("addCostDetails", addCostDetails);
        }
        return conditionApprovalVO;
    }

    /**
     * 待办任务激活
     *
     * @param workflowAgencyTaskCondition
     */
    @Override
    public void reActiveWorkflow(WorkflowAgencyTaskCondition workflowAgencyTaskCondition) {
        this.baseMapper.reActiveWorkflow(workflowAgencyTaskCondition);
    }

}
